package com.example.blog.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.example.blog.dao.ArticleDAO;
import com.example.blog.domain.Article;
import com.example.blog.domain.PageBean;
import com.example.blog.service.ArticleService;

@WebServlet("/listarticle")
public class ListArticleServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		// 1. 获取参数
		String pageStr = req.getParameter("page");
		String limitStr = req.getParameter("limit");
		if(pageStr==null)pageStr="1";
		if(limitStr==null)limitStr="10";
		
		int page = Integer.parseInt(pageStr);
		int limit = Integer.parseInt(limitStr);
		System.out.println("page"+page+",limit"+limit);
		
		// 2. 
//		ArticleDAO dao = new ArticleDAO();
//		List<Article> list = null;
//		try {
//			list = dao.findAll();
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		ArticleService service = new ArticleService();
		PageBean<Article> pageBean = service.queryPage(page, limit);
		
		// 3. 构建json
		Map<String,Object> map= new HashMap<>();
		map.put("code", 0);
		map.put("msg", "");
		map.put("page", page);
		map.put("limit", limit);
		map.put("count", pageBean.getCount());
		map.put("data",pageBean.getList());
		
		pw.print(JSON.toJSONString(map));
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}